package zhoug.common.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

/**
 * 电话状态监听广播
 * 只支持代码动态注册,需要权限{@link android.Manifest.permission#READ_PHONE_STATE}
 * @Author: zhoug
 * @Date: 2025-02-06
 * @Description:
 */
public class PhoneStateReceiver extends BroadcastReceiver {
    public static final String ACTION_PHONE_STATE_CHANGED = TelephonyManager.ACTION_PHONE_STATE_CHANGED;
    private Callback mCallback;

    public PhoneStateReceiver(Callback callback) {
        this.mCallback = callback;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (mCallback != null && ACTION_PHONE_STATE_CHANGED.equals(action)) {
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
                // 正在响铃,来电时才有效
                mCallback.onPhoneStateChange(Callback.RINGING);
            } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
                // 来电电话已接通，去电响铃,可以开始通话处理逻辑（例如更新UI）
                mCallback.onPhoneStateChange(Callback.STATE_OFFHOOK);
            } else if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
                // 电话已挂断，可以处理挂断后的逻辑（例如更新UI）
                mCallback.onPhoneStateChange(Callback.STATE_IDLE);
            }
        }
    }

    /**
     * 电话状态改变回掉
     */
    public interface Callback {
        /**
         * 来电响铃,来电时才有效
         */
        int RINGING = 1;
        /**
         * 来电电话已接通，去电响铃
         */
        int STATE_OFFHOOK = 2;
        /**
         * 电话已挂断
         */
        int STATE_IDLE = 3;

        /**
         * 电话状态改变
         *
         * @param status
         */
        void onPhoneStateChange(int status);

    }
}
